package com.spic.auth.controller;

import com.spic.auth.form.LoginBody;
import com.spic.auth.form.RegisterBody;
import com.spic.auth.service.SysLoginService;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.security.service.TokenService;
import com.spic.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Value("${remoteHostIp}")
    private String remoteHostIp;

    @Value("${remoteOuterHostIp}")
    private String remoteOuterHostIp;

    @Value("${enableSingleLogin}")
    private Boolean enableSingleLogin;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(),form.getCid(),form.getClientType());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo,form.getCid(),form.getTag(),remoteHostIp,remoteOuterHostIp,enableSingleLogin));
    }


    @PostMapping("loginApp")
    public R<?> loginApp(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(),form.getCid(),form.getClientType());
        // 获取登录token
        return R.ok(tokenService.createAppToken(userInfo,form.getCid(),form.getTag(),remoteHostIp,remoteOuterHostIp,enableSingleLogin));
    }


    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    @GetMapping("getHost")
    public String getHost(HttpServletRequest request){
        return tokenService.getHost(request,remoteHostIp,remoteOuterHostIp);
    }
}
